package com.jianbing.lakk.controller;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.jianbing.common.core.domain.entity.SysUser;
import com.jianbing.common.core.domain.model.LoginUser;
import com.jianbing.common.utils.SecurityUtils;
import com.jianbing.lakk.domain.LakkQuestionbank;
import com.jianbing.lakk.mapper.LakkQuestionbankMapper;
import com.jianbing.lakk.service.ILakkQuestionbankService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jianbing.common.annotation.Log;
import com.jianbing.common.core.controller.BaseController;
import com.jianbing.common.core.domain.AjaxResult;
import com.jianbing.common.enums.BusinessType;
import com.jianbing.lakk.domain.LakkUserprogress;
import com.jianbing.lakk.service.ILakkUserprogressService;
import com.jianbing.common.utils.poi.ExcelUtil;
import com.jianbing.common.core.page.TableDataInfo;
import com.jianbing.lakk.domain.LakkQuestionbank;
import com.jianbing.lakk.service.ILakkQuestionbankService;

/**
 * 用户进度Controller
 *
 * @author windbless
 * @date 2024-06-26
 */
@RestController
@RequestMapping("/lakk/UserProgress")
public class LakkUserprogressController extends BaseController {
    @Autowired
    private ILakkUserprogressService lakkUserprogressService;
    @Autowired
    private ILakkQuestionbankService lakkQuestionbankService;

    @GetMapping("/hasTellStory")
    public AjaxResult hasTellStory() {
        //先检查昨天是否需要讲故事
        LakkUserprogress yesterday = new LakkUserprogress();
        yesterday.setUserid(getappid(SecurityUtils.getLoginUser()));
        List<LakkUserprogress> list = lakkUserprogressService.selectLakkUserprogressList(yesterday);
        if (list.size() > 0) {
//            遍历每条记录 找到daynumber questionnumber最大的一条
            LakkUserprogress latest = list.get(0);
            for (LakkUserprogress lakkUserprogress1 : list) {
                if (lakkUserprogress1.getDaynumber() > latest.getDaynumber() || (lakkUserprogress1.getDaynumber() == latest.getDaynumber() && lakkUserprogress1.getQuestionnumber() > latest.getQuestionnumber())) {
                    latest = lakkUserprogress1;
                }
            }
            if (latest.getUseranswer() == null) {
//                未作答
                Long Tihao = latest.getQuestionnumber();
                LakkQuestionbank lakkQuestionbank = new LakkQuestionbank();
                lakkQuestionbank.setQuestionnumber(Tihao);
                List<LakkQuestionbank> lakkQuestionbanks = lakkQuestionbankService.selectLakkQuestionbankList(lakkQuestionbank);
                if (lakkQuestionbanks.size() > 0) {
                    if (lakkQuestionbanks.get(0).getQuestiontype().equals("编故事")) {
                        return success(latest);
                    } else {
                        return error("昨天不是讲故事");
                    }
                } else {
                    return error("题目数据不存在");
                }
            } else {
//                昨天最后一题已作答
                Long nowDAY = latest.getDaynumber() + 1;
                return error("昨天任务已作答，请生成今日任务");
//                查今天的题目的最后一题
//                LakkQuestionbank today = new LakkQuestionbank();
//                today.setDaynumber(nowDAY);
//                List<LakkQuestionbank> todayList = lakkQuestionbankService.selectLakkQuestionbankList(today);
//                if (todayList.size() > 0) {
//                    if (todayList.get(0).getQuestiontype().equals("编故事")) {
//                        return success(todayList.get(0));
//                    } else {
//                        return error("今天不是讲故事");
//                    }
//                } else {
//                    return error("已做完全部题库");
//                }
            }
        } else {
            return error("没有此用户进度信息");
        }


    }

    /**
     * 查询用户进度列表
     */
//    @PreAuthorize("@ss.hasPermi('lakk:UserProgress:list')")
    @GetMapping("/list")
    public TableDataInfo list(LakkUserprogress lakkUserprogress) {
        LoginUser nowLoginUser = SecurityUtils.getLoginUser();
        if (nowLoginUser == null) {
            ArrayList temp = new ArrayList<LakkUserprogress>();
            LakkUserprogress LakkUserprogresstemp = new LakkUserprogress();
            LakkUserprogresstemp.setUserid(1L);
            LakkUserprogresstemp.setUseranswer("您的账号还未登录");
            temp.add(LakkUserprogresstemp);
            return getDataTable(temp);
        } else {
            Long DepartmentId = nowLoginUser.getDeptId();
            if (DepartmentId == 202) {
                //测试账号无限生成
                LakkUserprogress yesterday = new LakkUserprogress();
                yesterday.setUserid(getappid(SecurityUtils.getLoginUser()));
                List<LakkUserprogress> list = lakkUserprogressService.selectLakkUserprogressList(yesterday);
                LakkUserprogress latest = null;
                if (list.size() > 0) {
                    //遍历每条记录 找到daynumber questionnumber最大的一条
                    latest = list.get(0);
                    for (LakkUserprogress lakkUserprogress1 : list) {
                        if (lakkUserprogress1.getDaynumber() > latest.getDaynumber() || (lakkUserprogress1.getDaynumber() == latest.getDaynumber() && lakkUserprogress1.getQuestionnumber() > latest.getQuestionnumber())) {
                            latest = lakkUserprogress1;
                        }
                    }
                }
                //把latest的daynumber的题目按照questionnumber排序并返回
                List<LakkUserprogress> list1 = new ArrayList<>();
                for (LakkUserprogress lakkUserprogress1 : list) {
                    if (lakkUserprogress1.getDaynumber() == latest.getDaynumber()) {
                        lakkUserprogress1.setQuestiontextsnapshot("测试账号无限生成");
                        list1.add(lakkUserprogress1);
                    }
                }
                return getDataTable(list1);
            }
            lakkUserprogress.setUserid(getappid(SecurityUtils.getLoginUser()));
            startPage();
            List<LakkUserprogress> list = lakkUserprogressService.selectLakkUserprogressList(lakkUserprogress);
            return getDataTable(list);
        }
    }

    @GetMapping("/list1")
    public TableDataInfo list1(LakkUserprogress lakkUserprogress) {
        startPage();
        List<LakkUserprogress> list = lakkUserprogressService.selectLakkUserprogressList(lakkUserprogress);
        return getDataTable(list);
    }

    private Long getappid(LoginUser loginUser) {
        return loginUser.getUserId();
    }

    /**
     * 导出用户进度列表
     */
//    @PreAuthorize("@ss.hasPermi('lakk:UserProgress:export')")
    @Log(title = "用户进度", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LakkUserprogress lakkUserprogress) {
        List<LakkUserprogress> list = lakkUserprogressService.selectLakkUserprogressList(lakkUserprogress);
        ExcelUtil<LakkUserprogress> util = new ExcelUtil<LakkUserprogress>(LakkUserprogress.class);
        util.exportExcel(response, list, "用户进度数据");
    }

    /**
     * 获取用户进度详细信息
     */
//    @PreAuthorize("@ss.hasPermi('lakk:UserProgress:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(lakkUserprogressService.selectLakkUserprogressById(id));
    }


    /**
     * 新增用户进度
     */
//    @PreAuthorize("@ss.hasPermi('lakk:UserProgress:add')")
    @Log(title = "用户进度", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LakkUserprogress lakkUserprogress) {
        return toAjax(lakkUserprogressService.insertLakkUserprogress(lakkUserprogress));
    }

    /**
     * 修改用户进度
     */
//    @PreAuthorize("@ss.hasPermi('lakk:UserProgress:edit')")
    @Log(title = "用户进度", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LakkUserprogress lakkUserprogress) {
        lakkUserprogress.setUserid(getappid(SecurityUtils.getLoginUser()));
        return toAjax(lakkUserprogressService.updateLakkUserprogress(lakkUserprogress));
    }

    /**
     * 删除用户进度
     */
//    @PreAuthorize("@ss.hasPermi('lakk:UserProgress:remove')")
    @Log(title = "用户进度", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(lakkUserprogressService.deleteLakkUserprogressByIds(ids));
    }

    @GetMapping("/getLatestProgress")
    public AjaxResult getLatestProgress() {
        LakkUserprogress lakkUserprogress = new LakkUserprogress();
        lakkUserprogress.setUserid(getappid(SecurityUtils.getLoginUser()));
        List<LakkUserprogress> list = lakkUserprogressService.selectLakkUserprogressList(lakkUserprogress);
        if (list.size() > 0) {
//            遍历每条记录 找到daynumber questionnumber最大的一条
            LakkUserprogress latest = list.get(0);
            for (LakkUserprogress lakkUserprogress1 : list) {
                if (lakkUserprogress1.getDaynumber() > latest.getDaynumber() || (lakkUserprogress1.getDaynumber() == latest.getDaynumber() && lakkUserprogress1.getQuestionnumber() > latest.getQuestionnumber())) {
                    latest = lakkUserprogress1;
                }
            }
            return success(latest);
        } else {
            return error("没有此用户进度信息");
        }
    }


    @GetMapping("/produceProgressThisDay")
    public AjaxResult produceProgressThisDay() {
        LoginUser nowLoginUser = SecurityUtils.getLoginUser();
        if (nowLoginUser == null) {
            return error("请先登录");
        } else {
            System.out.println("当前登录用户: " + nowLoginUser+"当前登录用户的部门: " + nowLoginUser.getDeptId());
            Long DepartmentId = nowLoginUser.getDeptId();
            if (DepartmentId == 202) {
                //测试账号无限生成

                LakkUserprogress temp = new LakkUserprogress();
                temp.setUserid(getappid(SecurityUtils.getLoginUser()));
                List<LakkUserprogress> list1 = lakkUserprogressService.selectLakkUserprogressList(temp);

                LakkUserprogress latest; // Declare latest here

                if (list1.size() > 0) {
                    // 遍历每条记录 找到daynumber questionnumber最大的一条
                    latest = list1.get(0); // list1, not list
                    for (LakkUserprogress lakkUserprogress1 : list1) { // list1, not list
                        if (lakkUserprogress1.getDaynumber() > latest.getDaynumber() ||
                                (lakkUserprogress1.getDaynumber() == latest.getDaynumber() &&
                                        lakkUserprogress1.getQuestionnumber() > latest.getQuestionnumber())) {
                            latest = lakkUserprogress1;
                        }
                    }
                    if (latest.getUseranswer() == null) {
                        return error("测试用户你好,请先回答昨天的问题");
                    }
                } else {
                    latest = new LakkUserprogress();
                    latest.setDaynumber(0L);
                }

                // 遍历题库
                LakkQuestionbank tiku = new LakkQuestionbank();
                tiku.setDaynumber(latest.getDaynumber() + 1);
                List<LakkQuestionbank> tikulist = lakkQuestionbankService.selectLakkQuestionbankList(tiku);


                if (tikulist.size() == 0) {
                    return error("测试用户你好,可做题都已经做完了");
                } else {
                    // 把tikuList按照questionnumber排序
                    tikulist.sort(Comparator.comparing(LakkQuestionbank::getQuestionnumber));
                    // 遍历每题，插入用户进度表
                    for (LakkQuestionbank lakkQuestionbank : tikulist) {
                        LakkUserprogress newProgress = new LakkUserprogress();
                        newProgress.setUserid(getappid(SecurityUtils.getLoginUser()));
                        newProgress.setDaynumber(latest.getDaynumber() + 1);
                        newProgress.setQuestionnumber(lakkQuestionbank.getQuestionnumber());
                        Date baseDate = new Date(2000 - 1900, 0, 1);
                        int daysToAdd = (int) (latest.getDaynumber() + 1);
                        long millisToAdd = daysToAdd * 24L * 60L * 60L * 1000L;
                        Date nowdate = new Date(baseDate.getTime() + millisToAdd);
                        newProgress.setCreationtime(nowdate);
                        lakkUserprogressService.insertLakkUserprogress(newProgress);
                    }

                    return success("测试用户你好，今日进度生成成功,共" + tikulist.size() + "题");
                }
            }else{
                  System.out.println("非测试用户");
            }
        }
        try {
            LakkUserprogress lakkUserprogress = new LakkUserprogress();
            lakkUserprogress.setUserid(getappid(SecurityUtils.getLoginUser()));
            Date date = new Date();
            date.setHours(0);
            date.setMinutes(0);
            date.setSeconds(0);
            lakkUserprogress.setCreationtime(date);
            List<LakkUserprogress> list = lakkUserprogressService.selectLakkUserprogressList(lakkUserprogress);

            if (list.size() > 0) {
                return error("今日进度已经生成");
            } else {
                LakkUserprogress temp = new LakkUserprogress();
                temp.setUserid(getappid(SecurityUtils.getLoginUser()));
                List<LakkUserprogress> list1 = lakkUserprogressService.selectLakkUserprogressList(temp);

                LakkUserprogress latest; // Declare latest here

                if (list1.size() > 0) {
                    // 遍历每条记录 找到daynumber questionnumber最大的一条
                    latest = list1.get(0); // list1, not list
                    for (LakkUserprogress lakkUserprogress1 : list1) { // list1, not list
                        if (lakkUserprogress1.getDaynumber() > latest.getDaynumber() ||
                                (lakkUserprogress1.getDaynumber() == latest.getDaynumber() &&
                                        lakkUserprogress1.getQuestionnumber() > latest.getQuestionnumber())) {
                            latest = lakkUserprogress1;
                        }
                    }
                } else {
                    latest = new LakkUserprogress();
                    latest.setDaynumber(0L);
                }

                // 遍历题库
                LakkQuestionbank tiku = new LakkQuestionbank();
                tiku.setDaynumber(latest.getDaynumber() + 1);
                List<LakkQuestionbank> tikulist = lakkQuestionbankService.selectLakkQuestionbankList(tiku);


                if (tikulist.size() == 0) {
                    return error("可做题都已经做完了");
                } else {
                    // 把tikuList按照questionnumber排序
                    tikulist.sort(Comparator.comparing(LakkQuestionbank::getQuestionnumber));
                    // 遍历每题，插入用户进度表
                    for (LakkQuestionbank lakkQuestionbank : tikulist) {
                        LakkUserprogress newProgress = new LakkUserprogress();
                        newProgress.setUserid(getappid(SecurityUtils.getLoginUser()));
                        newProgress.setDaynumber(latest.getDaynumber() + 1);
                        newProgress.setQuestionnumber(lakkQuestionbank.getQuestionnumber());
                        Date nowdate = new Date();
                        newProgress.setCreationtime(nowdate);
                        lakkUserprogressService.insertLakkUserprogress(newProgress);
                    }

                    return success("今日进度生成成功,共" + tikulist.size() + "题");
                }
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印堆栈跟踪
    return error("操作失败: " + e.getMessage());
        }
    }

}
